/**
 * 将AI产生的文本试题转换为JSON格式
 */
const PATTERN_TYPE = /^\[(单选题|多选题|判断题|填空题|简答题|不定项选择题)]/
const PATTERN_LEVEL = /^(难度|难度级别|难度等级)\s*[:：]\s*/
const PATTERN_ANALYSIS = /^(题目解析|解析|试题解析|试题答案解析|答案解析|题目答案解析)\s*[:：]\s*/
// 去除数字，如1.
const PATTERN_NUM = /^\d+\.\s*/
const PATTERN_ITEMS = /^[A-Za-z]\s*[、.]\s*/
const PATTERN_ANSWER = /^(答案)\s*[:：]\s*/
/**
 * 入口方法，将文本转换为JSON
 * @param text
 * @returns {*[]}
 */
export function textToJson(text) {
  const lines = text.split('\n').map(line => line.trim())

  const quList = []
  let currentQu = {}
  let nextContent = false
  let nextAnalysis = false

  for (const line of lines) {
    // 题干和题型
    if (PATTERN_TYPE.test(line)) {
      // 上一个内容入库
      if (currentQu.content) {
        quList.push(currentQu)
      }
      // 提取题干和题型
      const quType = mapQuType(line)
      // 去除题型和前面的题号
      const content = line.replace(PATTERN_TYPE, '').replace(PATTERN_NUM, '')
      currentQu = {
        content: content,
        answerList: [],
        analysis: '',
        quLevel: '',
        quType: quType,
        chapterId: ''
      }
      nextAnalysis = false
      nextContent = true
      continue
    }

    // 填充选项
    if (PATTERN_ITEMS.test(line)) {
      currentQu.answerList.push({ 'content': line, isRight: false })
      nextAnalysis = false
      nextContent = false
      continue
    }

    // 反填答案
    if (PATTERN_ANSWER.test(line)) {
      // 判断题单独处理
      if (currentQu.quType === 'judge') {
        currentQu.answerList = psJudgeItems(line)
      } else if (currentQu.quType === 'fill') {
        currentQu.answerList = psFillItems(line)
      } else {
        // 提取答案ABC数组
        const answers = extractLetters(line)
        // 匹配答案
        for (const an of answers) {
          for (let j = 0; j < currentQu.answerList.length; j++) {
            const item = currentQu.answerList[j]
            const regex = new RegExp(`^\\s*[${an.toLowerCase()}${an.toUpperCase()}][\\s:：.、].*`)
            if (regex.test(item.content)) {
              item.isRight = true
            }
          }
        }

        // 移除标识符
        for (let j = 0; j < currentQu.answerList.length; j++) {
          const item = currentQu.answerList[j]
          item.content = item.content.replace(PATTERN_ITEMS, '').trim()
        }
      }
      nextAnalysis = false
      nextContent = false
      continue
    }
    // 解析
    if (PATTERN_ANALYSIS.test(line)) {
      currentQu.analysis = line.replace(PATTERN_ANALYSIS, '')
      nextAnalysis = true
      nextContent = false
      continue
    }
    // 难度等级
    if (PATTERN_LEVEL.test(line)) {
      const quLevel = line.replace(PATTERN_LEVEL, '')
      currentQu.quLevel = mapQuLevel(quLevel)
      nextAnalysis = false
      nextContent = false
      continue
    }

    // 题干内容有换行的
    if (nextContent) {
      currentQu.content = currentQu.content + line
    }

    // 解析换行的
    if (nextAnalysis) {
      currentQu.analysis = currentQu.analysis + line
    }
  }

  // 加入最后一题
  if (currentQu.content) {
    quList.push(currentQu)
  }

  return quList
}


/**
 * 提取题型英文名称
 * @param text
 * @returns {*|null}
 */
export function mapQuType(text) {
  // 定义题型映射规则
  const typeMapping = {
    '单选题': 'radio',
    '多选题': 'multi',
    '不定项选择题': 'multi2',
    '判断题': 'judge',
    '填空题': 'fill',
    '简答题': 'saq'
  }

  // 正则匹配题型
  const match = text.match(PATTERN_TYPE)
  // 如果匹配成功，返回映射的英文名称；否则返回 null
  return match ? typeMapping[match[1]] : null
}

/**
 * 难易程度
 * @param text
 * @returns {*}
 */
export function mapQuLevel(text) {
  // 定义难度映射规则
  const typeMapping = {
    '简单': '1',
    '一般': '2',
    '较难': '3',
    '极难': '4'
  }
  return typeMapping[text]
}

/**
 * 提取答案的字母为数组
 * @param text
 * @returns {*|*[]}
 */
export function extractLetters(text) {
  // 使用正则表达式匹配字母
  const pattern = /[A-Za-z]/g
  const matches = text.match(pattern)
  return matches || [] // 如果匹配失败，返回空数组
}

/**
 * 处理判断题答案
 * @param text
 * @returns {[{content: string, isRight: boolean},{content: string, isRight: boolean}]}
 */
export function psJudgeItems(text) {
  const regex = /答案\s*[:：]\s*(正确|错误)/
  const result = text.match(regex)[1]
  // 填充答案
  return [
    { 'content': '正确', isRight: result === '正确' },
    { 'content': '错误', isRight: result === '错误' }]
}


/**
 * 处理填空题题答案
 * @param text
 * @returns {[{content: string, isRight: boolean},{content: string, isRight: boolean}]}
 */
export function psFillItems(text) {
  // 正则表达式匹配“答案:”后面的内容
  const regex = /答案\s*[：:](.+)/

  // 提取“答案:”后面的内容
  const match = text.match(regex)
  if (match) {
    // 将匹配的内容按 || 分割成数组
    const answers = match[1].split('\#\#')
    const answerList = []
    for (const an of answers) {
      answerList.push({ content: an, isRight: true })
    }
    return answerList
  } else {
    return []
  }
}
